/**
 * create by young (young2f@outlook.com) on 2023/4/16
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');

const moment = require('moment');

module.exports = class extends base {
  async findMany(body) {
    const { ctx } = this;
    console.log('find inbound', body);
    const { start, end, key, vendor, code } = body;
    const _key = key ? key : 'createdTs';
    if (start && end) {
      body[_key] = {
        $gte: new Date(moment(start)
          .valueOf()),
        $lt: new Date(moment(end)
          .valueOf())
      };
    }
    delete body['start'];
    delete body['end'];
    const sort = {};
    sort[_key] = -1;
    if (vendor) body['vendor'] = { $regex: vendor };
    if (code) body['code'] = { $regex: code };
    console.log('find inbound', body);
    const res = await ctx.app.dbs.aggregate('ProcureOrder', [
      { $match: { ...body } },
      { $sort: { ...sort } },
    ]);
    const result = [];
    _.map(res, item => {
      const { labels } = item;
      _.map(labels, it => {
        _.assign(item, it);
      });
      result.push(item);
    });
    return { status: 'ok', result };
  }

  async findOne(body) {
    const { ctx } = this;
    const { orderCode, tenantCode } = body;
    // const result = await ctx.app.dbs.findOne(table, body);
    const result = await ctx.app.dbs.findOne('ProcureOrder', { code: orderCode, tenantCode });
    // console.log('find inbound', result);
    result.orderCode = orderCode;
    return { status: 'ok', result };
  }

  /**
   * 入库批次只有删除，没有更新
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async updateOne(body) {
    // const { tenantCode, code } = body;
    // const { ctx } = this;
    // const result = await ctx.app.dbs.updateOne(table, { tenantCode, code }, body);
    // return { status: 'ok', result };
  }

  /**
   * 1、创建入库记录
   * 2、更新入库单数量
   * 3、更新采购单数量
   * 4、更新库存
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async createInboundLot(body) {
    console.log('createInboundLot', body);
    const { tenantCode, tenantName, orderCode, price, code, inboundCount, inboundDate, pmLotId } = body;
    const { ctx } = this;
    body['lotCount'] = body.inboundCount;
    body['lotDate'] = body.inboundDate;
    // body['boundOrderCode'] = body.inboundOrderCode;
    body['lotType'] = '入库';
    /**
     * 创建库存批次
     */
    delete body['_id'];
    const resultIn = await ctx.app.dbs.insert('InboundLot', body);

    /**
     * 更新采购物料批次
     */
    const result = await ctx.app.dbs.updateOne('ProcureMaterialRecord', { pmLotId }, {
      $inc: { inboundCount: inboundCount },
      inboundDate
    });

    const res2 = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: inboundCount } });
    //
    // const { inboundCount = 0 } = procureOrder;
    // const _count = parseInt(inboundCount) + parseInt(body.inboundCount);
    // const inboundDate = moment(body.inboundDate)
    //   .format('YYYY-MM-DD hh:mm:ss');
    // const updateCount1 = await ctx.app.dbs.updateOne('InboundOrder', { tenantCode, orderCode }, {
    //   inboundCount: _count,
    //   inboundDate
    // });
    // const updateCount2 = await ctx.app.dbs.updateOne('ProcureOrder', {
    //   tenantCode,
    //   code: orderCode
    // }, { inboundCount: _count, inboundDate });
    // /**
    //  * 更新物料库存
    //  */
    // const store = await ctx.app.dbs.findOne('Material', { tenantCode, code });
    //
    // let { storeCount = 0 } = store;
    // storeCount = parseInt(storeCount) + parseInt(body.inboundCount);
    // const result = updateCount2 && await ctx.app.dbs.updateOne('Material', { tenantCode, code }, {
    //   storeCount,
    //   price,
    //   updatedTs: new Date().valueOf()
    // });

    return { status: 'ok', result };


  }

  async findInboundLotMany(body) {
    const { ctx } = this;
    const result = await ctx.app.dbs.find('InboundLot', body);
    return { status: 'ok', result };
  }

  /**
   *
   * 2、更新入库单数量
   * 3、更新采购单数量
   * 4、更新库存
   * @param body
   * @returns {Promise<{result: *, status: string}>}
   */
  async deleteInboundLot(body) {
    const { ctx } = this;
    const { tenantCode, lotCode, pmLotId, inboundCount, code } = body;
    const resultIn = await ctx.app.dbs.deleteOne('InboundLot', { lotCode, tenantCode });
    console.log('deleteInboundLot', pmLotId, inboundCount);
    /**
     * 更新采购物料批次
     */
    const result = await ctx.app.dbs.updateOne('ProcureMaterialRecord', { pmLotId, tenantCode }, {
      $inc: { inboundCount: -inboundCount },
    });
    const res2 = await ctx.app.dbs.updateOne('Material', {
      code,
      tenantCode
    }, { $inc: { storeCount: -inboundCount } });
    return { status: 'ok', result };
  }
};
